﻿using System;

using Moe.ECamel.Common.Entities;
using Moe.ECamel.Client.Controllers;
using Moe.ECamel.Client.WinForms.Common;

namespace Moe.ECamel.Client.WinForms.Forms
{
	public partial class ECamelLoginForm : ECamelForm
	{
		private const int MaxAttempts = 3;
		private readonly SystemController _controller;
		private int _failedAttempts;

		public ECamelLoginForm()
		{
			InitializeComponent();
		}

		public ECamelLoginForm(SystemController controller)
			: this()
		{
			this._controller = controller;
			this._failedAttempts = 0;
		}

		private void ConfirmationButton_Click(object sender, EventArgs e)
		{
			var error = _controller.Login(UsernameTextBox.Text, PasswordTextBox.Text);
			if (error != null)
			{
				if (error.MessageId != MessageIds.SecurityInvalidCredentials)
					ECamelHelper.ShowMessage(error);
				else
				{
					// Update number of failed attempts:
					_failedAttempts++;
					// Handle failed attempt:
					if (_failedAttempts < MaxAttempts)
						ECamelHelper.ShowMessage(MessageIds.SecurityInvalidCredentials);
					else
					{
						ECamelHelper.ShowMessage(MessageIds.SecurityMaxAttemptsReached);
						this.Close();
					}	
				}				
			}
			else
			{
				this.Close();
			}
		}
		private void CancellationButton_Click(object sender, EventArgs e)
		{
			this.Close();
		}
	}
}